package br.ucb.musicbay.album;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;


public class AlbumDao implements AlbumInterfaceDao {

	private transient Session session;
	
	public void setSession(Session session){
		this.session = session;
	}
	
	@Override
	public boolean save(Album album) {
		try{
			this.session.save(album);
			return true;
		}catch(Exception e){
			throw new HibernateException("ERRO! ERRO - save(Album album) "+new Date());
		}
	}

	@Override
	public boolean delete(Album[] album) {
		try{
			for (Album album2 : album) {
				session.delete(album2);
			}
			return true;
		}catch (Exception e) {
			throw new HibernateException("ERRO! ERRO - delete(Album[] album) "+new Date());
		}	
	}

	@Override
	public boolean update(Album album) {		
		try{
			this.session.merge(album);
			return true;
		}catch(Exception e){
			throw new HibernateException("ERRO! ERRO - update(Album album) "+new Date());
		}
	}

	@Override
	public Album select(Album album) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Album> recoverAll() {
		Criteria criteria = this.session.createCriteria(Album.class).addOrder(Order.asc("artista"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Album> recoverAlbunsArtista(Integer idArtista) {
		Criteria criteria = this.session.createCriteria(Album.class).add(Restrictions.eq("id_artista", idArtista)).addOrder(Order.asc("nome"));
		return criteria.list();
	}

	@Override
	public Album recoverById(Integer id) {
		return (Album)session.get(Album.class,id);
	}

}
